package com.purchase.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

/**
 * 七牛
 * @author JiangShuai
 *
 */
public class QiniuUtil {

	/**
	 * 获取token
	 * @return
	 */
	public static String getToken() {
		String accessKey = PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"qiniu.AccessKey");
		String secretKey = PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"qiniu.SecretKey");
		String bucket = PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"qiniu.Bucket"); 
		Auth auth = Auth.create(accessKey, secretKey);

		StringMap putPolicy = new StringMap();
		putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
		long expireSeconds = 3600;
		//设置回传内容和有效时间3600s
		String upToken = auth.uploadToken(bucket, null, expireSeconds, null);
		return upToken;
	}
	
	/**
	 * @Title: getQiNiuUrl   
	 * @Description: 上传到七牛服务器  
	 * @param: @param localFilePath 图片路径
	 * @param: @return      
	 * @return: String
	 */
	public static String getQiNiuUrl(String localFilePath) {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone1());
		//...其他参数参考类注释

		UploadManager uploadManager = new UploadManager(cfg);
		//如果是Windows情况下，格式是 D:\\qiniu\\test.png
		//String localFilePath = "d:\\qiniu\\17928415052809.jpg";
		//默认不指定key的情况下，以文件内容的hash值作为文件名
		//String key = "17928415052809www.jpg";
		String key =null;
		
		String upToken = getToken();
		try {
		    Response response = uploadManager.put(localFilePath, key, upToken);
		    //System.out.println(response);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    //System.out.println(putRet.key);
		    return PropertiesUtil.getValue(PropertiesUtil.CONFPATH,"qiniu.urlheader")+putRet.key;
		    //System.out.println(putRet.hash);
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		        //ignore
		    }
		}
		return null;
	}
	
	public static void main(String[] args) {
		String localFilePath="D:\\qiniu\\lADPBbCc1T_5w9nNAgjNBKs_1195_520.jpg";
		String ii=getQiNiuUrl(localFilePath);
		System.out.println(ii);
	}
	
}
